package com.kim.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;


import java.io.InputStream;

//在.yml文件中的前缀
public class QiniuOssUitl {

        private static final String accessKey = "kb2YOCrdzN6Rn3aRlPe-2FGW_kGpMfuccdYQJ1Wm";
        private static final String secretKey = "8_BklP4w8jBmCbj6U94oWZfYE5Y3IryMGMQhxeDA";
        private static final String bucket = "kim42910";
        //指定区域节点
        private static final String regionNode = "qiniucs.com"; // 根据华东区域，选择合适的域名
/*七牛云常见区域的节点（域名）如下：

华东（Region.region0）：qiniucs.com
华北（Region.region1）：qiniudns.com
华南（Region.region2）：qiniuds.com
北美（Region.regionNa0）：qiniup.com
东南亚（Region.regionAs0）：qiniug.com
*/


    public static String uploadFile(String objectName, InputStream in) {
            //构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration(Region.region0());
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
            // ...其他参数参考类注释

            UploadManager uploadManager = new UploadManager(cfg);


            String url="";

            try {
            /* 注释掉默认上传 字符串，修改为自己的上传格式
            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);*/
                Auth auth = Auth.create(accessKey, secretKey);
                String upToken = auth.uploadToken(bucket);

                try {
                    Response response = uploadManager.put(in,objectName,upToken,null, null);
                    //解析上传成功的结果
                    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                    //url组成：https://bucket名称.区域节点/objectName
                    url = "https://"+bucket+"."+regionNode+"/"+objectName;

                    System.out.println(putRet.key);
                    System.out.println(putRet.hash);
                } catch (QiniuException ex) {
                    ex.printStackTrace();
                    if (ex.response != null) {
                        System.err.println(ex.response);

                        try {
                            String body = ex.response.toString();
                            System.err.println(body);
                        } catch (Exception ignored) {
                        }
                    }
                }
            } catch (Exception ex) {
                //ignore
            }
            return url;
        }
}

